package com.crazy.bookstore.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: 卢辉宇
 * @date: 2023/1/2 19:24
 * @description: 管理员登录过滤器
 */
public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //通过servletRequest的子接口拿到session
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        //判断是否登录
        if (session.getAttribute("member")==null){
            //通过HttpServletResponseWrapper的对象返回json数据给前端
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) servletRequest).getWriter();
            //向前端返回的json数据
            out.write("{\"status\":1007\",msg\":\"用户未登录\",\"data\":null}");
            //刷新并关闭
            out.flush();
            out.close();
            //不放行，提前结束
            return;
        }
        //是管理员登录,则放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
